<template>

  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <!-- 把部门负责人渲染上去 -->
        <el-option
          v-for="item in employees"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        size="small"
        @click="hSubmit"
      >确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { addDepartment, getDepartmentById, updateDepartment } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  props: {
    // 接收父组件传来的id
    getId: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    // 自定义校验
    const validCode = (rule, value, callback) => {
      console.log('自定义校验', value)
      let existCodeList = this.employees.map(item => item.code)

      // 如果是编辑状态,把当前部门的编码移除
      if (this.isEdit) {
        existCodeList = this.employees.filter(item => item.id !== this.id).map(item => item.code)
      }
      // 判断是否包含相同的code
      if (existCodeList.includes(value)) {
        callback(`有相同的${value}`)
      } else {
        callback()
      }
    }
    // 校验部门名称同级不重复
    const validName = (rule, value, callback) => {
      // 找到点击部门的子部门
      const existNameList = this.employees.filter(item => item.pid === this.id).map(item => item.name)
      //  判断当前用户输入的名臣是否已经存在数组内
      if (existNameList.includes(value)) {
        callback(new Error(`该部门名称:${value}已经存在`))
      } else {
        callback()
      }
    }
    return {
      employees: [], // 存放简单员工信息
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门负责人
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '部门名称要求1-10个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '部门编码要求1-10个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadEmployeeSimple() // 触发简单员工信息
    if (this.isEdit) {
      this.loadUpdateDepartment() // 触发根据id修改部门
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    // 发送请求:根据id编辑数据
    async loadUpdateDepartment() {
      try {
        const res = await getDepartmentById(this.getId)
        console.log('编辑部门', res)
        if (res.code === 10000) {
          this.form = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 发送请求:简单员工信息
    async loadEmployeeSimple() {
      try {
        const res = await getEmployeeSimple()
        console.log('简单员工信息', res.data)
        this.employees = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 发送请求: 新增部门
    async doAdd() {
      try {
        const newForm = { ...this.form, pid: this.getId }
        console.log('newForm', newForm)
        const res = await addDepartment(newForm)
        // console.log('新增部门新增部门')
        console.log('新增部门', res)
        if (res.code !== 10000) return this.$message.error(res.message) // 失败
        this.$message.success(res.message) // 成功
        // 子传父,最终渲染是在父组件呈现
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑部门
    async doEdit() {
    //  上面得到修改以后的数据传给form 这里需要再次请求,渲染
      try {
        const res = await updateDepartment(this.form)
        console.log('修改以后的数据', res)
        if (res.code === 10000) {
          // 渲染 关闭弹窗
          this.$emit('success')
        }
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
    /* // 3元判定,true就是编辑,false就是新增
      this.isEdit ? this.doEdit() : this.doAdd() */
      // 兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return // 校验失败
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消
    hCancel() {
      // 子传父关闭弹层
      this.$emit('close')
    }
  }
}
</script>

<style>

</style>
